using System;
using System.Collections.Generic;
using System.Xml;
using System.Data;
using System.Diagnostics;
using Adoor.Expression;
using Adoor.Object;
using Adoor.Object.Entity;
using Adoor.Relational;
using Adoor.Data;  // For SmartKey


namespace Adoor.Object.Relational
{
    public class CustomKeyMapping<TEntity> : OidData<TEntity>
    {
        public CustomKeyMapping(Adoor.Object.Domain.EntityData factory, XmlNode metadata)
            : base(factory, metadata)
        {
        }

        public override string GetOid(KeyValue key)
        {
            if (key.Values == null)
                return null;
            // only works in the absence of inheritance, or when key.Values.Length == 1
            System.Text.StringBuilder result = new System.Text.StringBuilder();
            foreach (object o in key.Values)
            {
                if (result.Length != 0)
                    result.Append(':');
                result.Append(o);
                if (o == DBNull.Value)
                    return null;
            }

            return result.ToString();
        }

        public override KeyValue ExtractKey(string oid)
        {
            string[] s = oid.Split(':');
            object[] result = new object[s.Length];
            int i = 0;
            foreach (DataColumn dc in this.DataColumns)
            {
                result[i] = Convert.ChangeType(s[i], dc.DataType);
                ++i;
            }
            return new KeyValue(result);
        }

        //		public override EntityData GetActualEntityData2(string oid)
        //		{
        //			return this.EntityData;
        //		}
    }

}
